package org.duang.http.core;

import java.util.concurrent.Future;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.nio.client.HttpAsyncClient;
import org.duang.http.common.ClientException;
import org.duang.kit.ToolsKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultServiceClient extends ServiceClient {
	
	private static Logger logger = LoggerFactory.getLogger(DefaultServiceClient.class);
	private HttpAsyncClient httpClient;
	
	public DefaultServiceClient() {
		super();
		try{
			httpClient = HttpFactory.createHttpAsyncClient(config);
			start();		//启动
		} catch (Exception e) {
			e.printStackTrace();
			logger.warn(e.getMessage());
			throw new ClientException(e.getMessage(),e);
		}
	}

	protected <T> Future<HttpResponse> sendRequestImpl(Request request, HttpCallBack<T> callback) throws Exception {
		if(ToolsKit.isEmpty(request) && ToolsKit.isEmpty(request.getContent())){
			throw new ClientException("request or content is null");
		}
		HttpRequestBase httpRequest = HttpFactory.createHttpRequest(request);
		Future<HttpResponse> future = httpClient.execute(httpRequest, callback);
//		httpRequest.releaseConnection();
		return future;
	}
	
	public void start() {
		if (ToolsKit.isNotEmpty(httpClient) && httpClient instanceof CloseableHttpAsyncClient) {
			try{
				((CloseableHttpAsyncClient)httpClient).start();
			} catch (Exception e) {
				logger.warn(e.getMessage(), e);
			}
		}
	}
	
	public void close() {
		if (ToolsKit.isNotEmpty(httpClient) && httpClient instanceof CloseableHttpAsyncClient) {
			try{
				((CloseableHttpAsyncClient)httpClient).close();
			} catch (Exception e) {
				logger.warn(e.getMessage(), e);
			}
		}
	}
}
